package so.shanku.essential.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import aym.util.getservicesdata.GetServicesDataQueue;
import aym.util.getservicesdata.GetServicesDataUtil;
import aym.util.json.JsonMap;
import aym.util.json.JsonParseHelper;
import com.lidroid.xutils.ViewUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import net.tsz.afinal.annotation.view.ViewInject;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseUIActivity;
import so.shanku.essential.adapter.ApplyReturnProductAdapter;
import so.shanku.essential.app.MyApplication;
import so.shanku.essential.getdata.GetDataConfing;
import so.shanku.essential.getdata.GetDataQueue;
import so.shanku.essential.getdata.JsonKeys;
import so.shanku.essential.getdata.ShowGetDataError;
import so.shanku.essential.utils.*;
import so.shanku.essential.view.ListViewNoScroll;

import java.io.File;
import java.util.*;

/**
 * Created by admin on 15/10/26.
 */
public class ApplyReturnProductActivity extends BaseUIActivity implements ApplyReturnProductAdapter.ItemCompountClickListener {
	@ViewInject(id = R.id.tv_order_num)
	private TextView orderNum_tv;
	@ViewInject(id = R.id.return_goods_ed)
	private EditText return_goods_ed;
	@ViewInject(id = R.id.btn_confirm, click = "btn_confirm_click")
	private Button confirm_bt;
	/**
	 * 订单编号
	 */
	private String order_num_str;

	@ViewInject(id = R.id.attach_pic_layout)
	private LinearLayout attach_pic_layout;

	@ViewInject(id = R.id.add_pic_iv, click = "add_pic_iv_click")
	private ImageView add_pic_iv;

	/**
	 * 段落 item view
	 */
	private HashMap<Integer, PhasesViewHolder> phasesView = new HashMap<Integer, PhasesViewHolder>();
	private HashMap<Integer, String> attachPics = new HashMap<Integer, String>();
	/**
	 * 已经添加过的 段落索引
	 */
	private int phasesIndex = 0;
	/**
	 * 添加图片 点击的条目位置
	 */
	Integer tag;

	@ViewInject(id = R.id.goods_lv)
	private ListViewNoScroll goods_lv;
	private ApplyReturnProductAdapter goodsListAdapter;
	private ArrayList<JsonMap<String, Object>> datas;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.apply_returngoods_layout);
		setCenter_title(R.string.apply_goods_return);
		order_num_str = getIntent().getStringExtra(ExtraKeys.Key_Msg1);
		orderNum_tv.setText(order_num_str);
		getRetunGoods();
	}

	/**
	 * 获取商品 信息
	 * {OrderNum
	 * :”xxxxxxx”}
	 */
	private void getRetunGoods() {
		loadingToast.show();

		Map<String, Object> params = new HashMap<String, Object>();
		params.put(GetDataQueue.Params_key, GetDataConfing.Key_Str);
		params.put("OrderNum", order_num_str);

		GetDataQueue queue = new GetDataQueue();
		queue.setCallBack(callBack);
		queue.setActionName(GetDataConfing.Action_RetunGoods);
		queue.setWhat(GetDataConfing.What_RetunGoods);
		queue.setParamsNoJson(params);
		getDataUtil.getData(queue);
	}

	/**
	 * 选择图片
	 *
	 * @param view
	 */
	public void add_pic_iv_click(View view) {
		showModPhotosView();
	}


	public PopupWindow popupWindow;
	private Button select_photo_camera_bt;
	private Button select_photo_local_bt;
	private final int select_local_requestcode = 1;
	private final int select_camera_requestcode = 3;
	private final int crop_requestcode = 4;
	/**
	 * 存放照片的文件
	 */
	private File image;

	private void showModPhotosView() {
		if (popupWindow == null) {
			View view = getLayoutInflater().inflate(R.layout.select_photo, null);
			popupWindow = new PopupWindow(view,
					ViewGroup.LayoutParams.MATCH_PARENT,
					ViewGroup.LayoutParams.MATCH_PARENT);
			popupWindow.setContentView(view);
			popupWindow.setAnimationStyle(R.style.popupAnimation);
			select_photo_camera_bt = (Button) view
					.findViewById(R.id.select_photo_camera_bt);
			select_photo_local_bt = (Button) view
					.findViewById(R.id.select_photo_local_bt);
			View select_v = view.findViewById(R.id.select_v);
			select_photo_local_bt.setOnClickListener(cameraClick);
			select_photo_camera_bt.setOnClickListener(cameraClick);
			select_v.setOnClickListener(cameraClick);
			popupWindow.showAtLocation(orderNum_tv, Gravity.NO_GRAVITY, 0, 0);

		} else if (!popupWindow.isShowing()) {
			popupWindow.showAtLocation(orderNum_tv, Gravity.NO_GRAVITY, 0, 0);
		}
	}

	@Override
	public void onBackPressed() {
		if (popupWindow != null && popupWindow.isShowing()) {
			popupWindow.dismiss();
		} else {
			super.onBackPressed();
		}
	}

	private View.OnClickListener cameraClick = new View.OnClickListener() {
		@Override
		public void onClick(View view) {
			int id = view.getId();
			if (id == R.id.select_photo_local_bt) {

				Intent intent = CropImage.getImageIntent();
				startActivityForResult(intent, select_local_requestcode);

				popupWindow.dismiss();
			} else if (id == R.id.select_photo_camera_bt) {
				startCamera(select_camera_requestcode);
			}
			popupWindow.dismiss();
		}
	};

	private void startCamera(int position) {
		Intent intent = new Intent();
		intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
		if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			return;
		}
		File file = new File(Confing.productPath
				+ "/MyPhoto");
		if (!file.exists()) {
			file.mkdirs();
		}
		image = new File(file, "myphoto.jpg");
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image));

		startActivityForResult(intent, position);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == Activity.RESULT_OK) {
			loadingToast.show();
			loadingToast.update(R.string.upload_goods_pic_ing);
			switch (requestCode) {
				case select_camera_requestcode:
					try {
						/* 将Bitmap设定到ImageView */
						Bitmap bitmap = BitmapHelper.resizeImage(image.getAbsolutePath(), 480, 854);
						upLoadUserPic(bitmap);
					} catch (Exception e) {
						loadingToast.dismiss();
						toast.showToast(R.string.user_updata_pic_error);
					}
					break;
				case select_local_requestcode:
					Uri selectedImage = data.getData();
					String imagePath = PicHelper.getPath(mContext, selectedImage); // 获取图片的绝对路径
					try {
						/* 将Bitmap设定到ImageView */
						Bitmap bitmap = BitmapHelper.resizeImage(imagePath, 480, 854);
						upLoadUserPic(bitmap);
					} catch (Exception e) {
						loadingToast.dismiss();
						toast.showToast(R.string.user_updata_pic_error);
					}
					break;
			    /* 将Bitmap设定到ImageView */
				case crop_requestcode:
					try {
						/* 将Bitmap设定到ImageView */
						Bitmap bitmap = data.getParcelableExtra("data");
						bitmap = BitmapHelper.resizeImage(bitmap, 480, 854);
						upLoadUserPic(bitmap);
					} catch (Exception e) {
						loadingToast.dismiss();
						toast.showToast(R.string.user_updata_pic_error);
					}
					break;
				default:
					break;
			}
		}
	}

	/**
	 * 上传用户头像 (调用接口)
	 */
	private void upLoadUserPic(Bitmap bitmap) {
		byte[] isbt = BitmapHelper.compressBitmap(bitmap, 2 * 1024 * 1024);
		String uploadBuffer = new String(Base64.encode(
				isbt, Base64.DEFAULT)); // 进行Base64编码
		String fileType = "png";

		Map<String, Object> params = new HashMap<String, Object>();
		params.put(GetDataQueue.Params_key, GetDataConfing.Key_Str);
		params.put("PicPath", uploadBuffer);
		params.put("imgType", fileType);
		GetDataQueue queue = new GetDataQueue();
		queue.setActionName(GetDataConfing.Action_ImgUp);
		queue.setParamsNoJson(params);
		queue.setCallBack(new GetServicesDataUtil.IGetServicesDataCallBack() {
			@Override
			public void onLoaded(GetServicesDataQueue entity) {
				if (entity.isOk()) {
					if (ShowGetDataError.isOkAndCodeIsNot1(mContext,
							entity.getInfo())) {
						toast.showToast(R.string.uploading_success);
						List<JsonMap<String, Object>> data = JsonParseHelper.getJsonMap_List_JsonMap(
								entity.getInfo(), JsonKeys.Key_Info);
						String headerPicPath = data.get(0).getStringNoNull("PicPath");
						addPicView(headerPicPath);
					}
				} else {
					ShowGetDataError.showNetError(mContext);
				}
				loadingToast.dismiss();
			}
		});
		getDataUtil.getData(queue);
	}


	/**
	 * 显示上图的
	 *
	 * @param picPath 图片路径
	 */
	private void addPicView(String picPath) {
		View view = getLayoutInflater().inflate(R.layout.attach_pic_item, null);
		PhasesViewHolder phasesViewHolder = new PhasesViewHolder();
		ViewUtils.inject(phasesViewHolder, view);
		view.setTag(phasesIndex);
		phasesViewHolder.del_pic_iv.setTag(phasesIndex);
		phasesViewHolder.del_pic_iv.setOnClickListener(clickListener);
		ImageLoader.getInstance().displayImage(StringUtil.get_SImage(picPath), phasesViewHolder.attach_pic_iv, MyApplication.getInstance().getBrandDefaultOption());
		attach_pic_layout.addView(view, 1);
		phasesView.put(phasesIndex, phasesViewHolder);
		attachPics.put(phasesIndex, picPath);
		phasesIndex++;
	}

	View.OnClickListener clickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			tag = (Integer) v.getTag();
			int id = v.getId();
			if (id == R.id.del_pic_iv) {
				del_phase(tag);
			}
		}
	};

	/**
	 * 根据tag 取view在container中位置
	 *
	 * @param tag
	 * @return
	 */
	private int viewIndexInContainer(Integer tag) {
		int childNum = attach_pic_layout.getChildCount();

		for (int i = 1; i < childNum; i++) {
			View view1 = attach_pic_layout.getChildAt(i);
			Integer viewTag = (Integer) view1.getTag();
			if (tag.intValue() == viewTag.intValue()) {
				return i;
			}
		}
		return -1;
	}

	/**
	 * 删除上传的图片
	 *
	 * @param tag
	 */
	private void del_phase(Integer tag) {
		int position = viewIndexInContainer(tag);
		attach_pic_layout.removeViewAt(position);
		attachPics.remove(tag);
		phasesView.remove(tag);
	}

	/**
	 * 图片 item
	 */
	class PhasesViewHolder {
		@com.lidroid.xutils.view.annotation.ViewInject(R.id.attach_pic_iv)
		ImageView attach_pic_iv;
		@com.lidroid.xutils.view.annotation.ViewInject(R.id.del_pic_iv)
		ImageView del_pic_iv;
	}


	/**
	 * 申请退货
	 *
	 * @param view
	 */
	public void btn_confirm_click(View view) {
		String returnReason = return_goods_ed.getText().toString();
		if (TextUtils.isEmpty(returnReason)) {
			toast.showToast(R.string.input_return_reason);
			return;
		}
		boolean isInValid = true;
		for (JsonMap jsonMap : datas) {
			if (jsonMap.getInt("ReturnCount") > 0) {
				isInValid = false;
				break;
			}
		}
		if (isInValid) {
			toast.showToast(R.string.return_goods_num_all_error);
			return;
		}
//		if (attachPics.size() == 0) {
//			toast.showToast(R.string.attach_null);
//			return;
//		}
		loadingToast.show();
		loadingToast.update(R.string.fill_return_uploading);

		ArrayList<HashMap<String, String>> attachPicArray = new ArrayList<HashMap<String, String>>();
		Iterator entryIterator = attachPics.entrySet().iterator();

		while (entryIterator.hasNext()) {
			Map.Entry entry = (Map.Entry) entryIterator.next();
			String value = (String) entry.getValue();
			JsonMap jsonMap = new JsonMap();
			jsonMap.put("ImgPath", value);
			attachPicArray.add(jsonMap);
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(GetDataQueue.Params_key, GetDataConfing.Key_Str);
		params.put("OrderNum", order_num_str);
		params.put("ReturnReason", returnReason);
		params.put("UserInfoId", Utils.getUserId(mContext));
		params.put("GoosImgslList", attachPicArray);
		params.put("RefundGoodInfo", datas);
		params.put("ExpressCompany", "");
		params.put("LogisticsNum", "");


		GetDataQueue queue = new GetDataQueue();
		queue.setActionName(GetDataConfing.Action_ApplyReturnGoods);
		queue.setCallBack(callBack);
		queue.setParamsNoJson(params);
		queue.setWhat(GetDataConfing.What_ApplyReturnGoods);
		getDataUtil.getData(queue);
	}


	/**
	 * 获取服务器数据的返回信息
	 */
	private GetServicesDataUtil.IGetServicesDataCallBack callBack = new GetServicesDataUtil.IGetServicesDataCallBack() {
		@Override
		public void onLoaded(GetServicesDataQueue entity) {
			if (entity.isOk()) {
				if (ShowGetDataError.isOkAndCodeIsNot1(mContext,
						entity.getInfo())) {
					if (entity.what == GetDataConfing.What_ApplyReturnGoods) {
						//setOrderDetail(data);
						toast.showToast(R.string.fill_return_reason_success);
						finish();
					} else if (entity.what == GetDataConfing.What_RetunGoods) {
//						{"Code":0,"Msg":"ok","Info":[{"ProductId":（商品编号）,
//							" Name（商品名称）"ProductUrl":null,"FactPrice（价格）
//							"Path（图片路径）Amount（数量）" +
//									"speStrName（规格）,"Skuid"（规格ID）}]}
						JsonMap jsonMap = JsonParseHelper.getJsonMap_JsonMap(entity.getInfo(), JsonKeys.Key_Info);

						datas = (ArrayList<JsonMap<String, Object>>) jsonMap.getList_JsonMap("OrderDetailVOList");
						setGoodsAdapter();
					}
				}
			} else {
				ShowGetDataError.showNetError(mContext);
			}
			loadingToast.dismiss();
		}
	};

	private void setGoodsAdapter() {
		for (int i = 0; i < datas.size(); i++) {
			JsonMap jsonMap = datas.get(i);
			int needReturn = jsonMap.getInt("Amount") - jsonMap.getInt("ReturnAmout");
			datas.get(i).put("NeedReturn", needReturn);
			datas.get(i).put("ReturnCount", needReturn);
		}
		goodsListAdapter = new ApplyReturnProductAdapter(this);
		goodsListAdapter.setItemCompountClickListener(this);
		goodsListAdapter.setDatas(datas);
		goods_lv.setAdapter(goodsListAdapter);
	}


	@Override
	public void itemCompountClick(Constant.ShopCartItemCompontType shopCartitemType, int index) {
		if (shopCartitemType == Constant.ShopCartItemCompontType.ADD_NUM) {
			goodsNumChange(shopCartitemType, index);
		} else if (shopCartitemType == Constant.ShopCartItemCompontType.SUB_NUM) {
			goodsNumChange(shopCartitemType, index);
		} else if (shopCartitemType == Constant.ShopCartItemCompontType.NUM_EDIT) {
			showEditNumDialog(shopCartitemType, index);
		} else if (shopCartitemType == Constant.ShopCartItemCompontType.CLICK_GOODS_ITEM) {
			showGoodsDetail(index);
		}
	}


	/**
	 * 跳转到商品详情
	 *
	 * @param index
	 */
	private void showGoodsDetail(int index) {
		JsonMap jsonMap = datas.get(index);
		Bundle bundle = new Bundle();
		bundle.putString(Constant.ID, jsonMap.getStringNoNull("ProductId"));
		//bundle.putString(Constant.NAME,jsonMap.getStringNoNull("ShopName"));
		jumpTo(ProductDetailActivity.class, bundle, false);
	}


	private void goodsNumChange(Constant.ShopCartItemCompontType shopCartitemType, int index) {

		JsonMap jsonMap = datas.get(index);
		int num = jsonMap.getInt("ReturnCount");
		if (shopCartitemType == Constant.ShopCartItemCompontType.ADD_NUM) {
			if (num >= jsonMap.getInt("NeedReturn")) {
				return;
			}
			num++;
		} else {
			if (num <= 0) {
				return;
			}
			num--;
		}
		//String productId = jsonMap.getStringNoNull("ProductId");
		updateGoodsNum(num, index);
	}

	/**
	 * 更新数量
	 *
	 * @param num
	 * @param position 商品位置
	 */
	private void updateGoodsNum(int num, int position) {
		datas.get(position).put("ReturnCount", num);
		goodsListAdapter.notifyDataSetChanged();
	}

	private Dialog dialogLogin;
	private EditText et_product_pronum;
	private ImageView iv_pronum_jian;
	private ImageView iv_pronum_jia;
	private ImageView bt_quxiao;
	private ImageView bt_queding;
	private TextView tv_price;
	private TextView tv_pronum;
	private TextView tip_tv;
	int pronum;

	private void showEditNumDialog(Constant.ShopCartItemCompontType shopCartitemType, final int index) {
		final JsonMap jsonMap = datas.get(index);
		dialogLogin = new Dialog(this, R.style.ShopDialogStyle);
		dialogLogin.setCanceledOnTouchOutside(false);
		dialogLogin.setCancelable(true);
		View view = getLayoutInflater().inflate(R.layout.item_shoppingcart_editnum, null);
		et_product_pronum = (EditText) view
				.findViewById(R.id.i_s_et_product_pronum);
		iv_pronum_jian = (ImageView) view
				.findViewById(R.id.i_s_iv_pronum_jian);
		iv_pronum_jia = (ImageView) view
				.findViewById(R.id.i_s_iv_pronum_jia);
		bt_quxiao = (ImageView) view
				.findViewById(R.id.i_s_bt_quxiao);
		bt_queding = (ImageView) view
				.findViewById(R.id.i_s_bt_queding);
		tv_price = (TextView) view
				.findViewById(R.id.i_s_tv_price);
		tip_tv = (TextView) view.findViewById(R.id.tip_tv);
		tv_pronum = (TextView) view
				.findViewById(R.id.i_s_tv_pronum);
		dialogLogin.setContentView(view);

		tv_price.setText(StringUtil.getFormatMoneyWithSign(jsonMap.getStringNoNull("ProductPrice")));
		tip_tv.setText(R.string.return_goods_num);
		et_product_pronum.setText(jsonMap.getStringNoNull("ReturnCount"));
		tv_pronum.setVisibility(View.GONE);
		tv_price.setVisibility(View.GONE);
		// tv_pronum.setText("x" + et_product_pronum.getText());
		dialogLogin.show();

		iv_pronum_jia.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				pronum = Integer.parseInt(et_product_pronum
						.getText().toString());
				if (pronum < jsonMap.getInt("NeedReturn")) {
					pronum++;
					show();
					return;
				}


			}
		});
		iv_pronum_jian
				.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {

						pronum = Integer
								.parseInt(et_product_pronum
										.getText().toString());
						if (pronum > 0) {
							pronum = pronum - 1;
							show();
						}

					}
				});
		bt_quxiao.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				dialogLogin.cancel();
			}
		});

		bt_queding.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!"".equals(et_product_pronum.getText()
						.toString())) {
					pronum = Integer.parseInt(et_product_pronum
							.getText().toString());
					JsonMap jsonMap = datas.get(index);
					if (pronum > jsonMap.getInt("NeedReturn")) {
						toast.showToast(R.string.num_invalid);
						return;
					} else if (pronum < 0) {
						toast.showToast(R.string.num_invalid);
						return;
					}
					updateGoodsNum(pronum, index);
					//String productId = jsonMap.getStringNoNull("ProductId");
				}


			}
		});
	}

	public void show() {
		et_product_pronum.setText(pronum + "");
		// tv_pronum.setText(pronum + "");
	}
}